[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName } from '~/client/services/layout';
  19. import { Comments } from '~/components/Comments';
  20. import { MainPane } from '~/components/Layout/MainPane';
  21. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  22. // import { useTranslation } from '~/i18n';
  23. import { PageContentFooter } from '~/components/PageContentFooter';
  24. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  25. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  26. import type { CrowiRequest } from '~/interfaces/crowi-request';
  27. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  28. // import { useRendererSettings } from '~/stores/renderer';
  29. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  30. import type { EditorConfig } from '~/interfaces/editor-settings';
  31. import type { RendererConfig } from '~/interfaces/services/renderer';
  32. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  33. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  34. import type { PageModel, PageDocument } from '~/server/models/page';
  35. import type { PageRedirectModel } from '~/server/models/page-redirect';
  36. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  37. import { useEditingMarkdown } from '~/stores/editor';
  38. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  39. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  40. import { useRedirectFrom } from '~/stores/page-redirect';
  41. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  42. import {
  43. useSelectedGrant,
  44. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  45. } from '~/stores/ui';
  46. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  47. import loggerFactory from '~/utils/logger';
  48. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  49. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  50. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  51. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  52. import { BasicLayoutWithEditorMode } from '../components/Layout/BasicLayout';
  53. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  54. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  55. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  56. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  57. import type { PageSideContentsProps } from '../components/PageSideContents';
  58. import {
  59. useCurrentUser,
  60. useIsLatestRevision,
  61. useIsForbidden, useIsNotFound, useIsSharedUser,
  62. useIsEnabledStaleNotification, useIsIdenticalPath,
  63. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  64. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  65. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  66. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  67. useIsSlackConfigured, useRendererConfig,
  68. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  69. } from '../stores/context';
  70. import { NextPageWithLayout } from './_app.page';
  71. import {
  72. CommonProps, getNextI18NextConfig, getServerSideCommonProps, generateCustomTitle,
  73. } from './utils/commons';
  74. declare global {
  75. // eslint-disable-next-line vars-on-top, no-var
  76. var globalEmitter: EventEmitter;
  77. }
  78. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  79. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  80. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  81. const PageSideContents = dynamic<PageSideContentsProps>(() => import('../components/PageSideContents').then(mod => mod.PageSideContents), { ssr: false });
  82. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  83. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  84. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  85. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  86. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  87. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  88. const logger = loggerFactory('growi:pages:all');
  89. const {
  90. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isCreatablePage, isTopPage,
  91. } = pagePathUtils;
  92. const { removeHeadingSlash } = pathUtils;
  93. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  94. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  95. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  96. {
  97. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  98. return v?.data != null
  99. && v?.data.toObject != null
  100. && v?.meta != null
  101. && isIPageInfoForEntity(v.meta);
  102. },
  103. serialize: (v) => {
  104. return {
  105. data: superjson.stringify(v.data.toObject()),
  106. meta: superjson.stringify(v.meta),
  107. };
  108. },
  109. deserialize: (v) => {
  110. return {
  111. data: superjson.parse(v.data),
  112. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  113. };
  114. },
  115. },
  116. 'IPageToShowRevisionWithMetaTransformer',
  117. );
  118. const IdenticalPathPage = (): JSX.Element => {
  119. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  120. return <IdenticalPathPage />;
  121. };
  122. const PutbackPageModal = (): JSX.Element => {
  123. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  124. return <PutbackPageModal />;
  125. };
  126. type Props = CommonProps & {
  127. currentUser: IUser,
  128. pageWithMeta: IPageToShowRevisionWithMeta | null,
  129. // pageUser?: any,
  130. redirectFrom?: string;
  131. // shareLinkId?: string;
  132. isLatestRevision?: boolean,
  133. isIdenticalPathPage?: boolean,
  134. isForbidden: boolean,
  135. isNotFound: boolean,
  136. isNotCreatable: boolean,
  137. // isAbleToDeleteCompletely: boolean,
  138. templateTagData?: string[],
  139. templateBodyData?: string,
  140. isSearchServiceConfigured: boolean,
  141. isSearchServiceReachable: boolean,
  142. isSearchScopeChildrenAsDefault: boolean,
  143. isSlackConfigured: boolean,
  144. // isMailerSetup: boolean,
  145. isAclEnabled: boolean,
  146. // hasSlackConfig: boolean,
  147. drawioUri: string | null,
  148. hackmdUri: string,
  149. noCdn: string,
  150. // highlightJsStyle: string,
  151. isAllReplyShown: boolean,
  152. isContainerFluid: boolean,
  153. editorConfig: EditorConfig,
  154. isEnabledStaleNotification: boolean,
  155. isEnabledAttachTitleHeader: boolean,
  156. // isEnabledLinebreaks: boolean,
  157. // isEnabledLinebreaksInComments: boolean,
  158. adminPreferredIndentSize: number,
  159. isIndentSizeForced: boolean,
  160. disableLinkSharing: boolean,
  161. rendererConfig: RendererConfig,
  162. // UI
  163. userUISettings?: IUserUISettings
  164. // Sidebar
  165. sidebarConfig: ISidebarConfig,
  166. };
  167. const Page: NextPageWithLayout<Props> = (props: Props) => {
  168. // const { t } = useTranslation();
  169. const router = useRouter();
  170. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  171. // register global EventEmitter
  172. if (isClient() && window.globalEmitter == null) {
  173. window.globalEmitter = new EventEmitter();
  174. }
  175. // commons
  176. useEditorConfig(props.editorConfig);
  177. useCsrfToken(props.csrfToken);
  178. // UserUISettings
  179. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  180. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  181. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  182. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  183. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  184. // page
  185. useIsLatestRevision(props.isLatestRevision);
  186. useIsContainerFluid(props.isContainerFluid);
  187. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  188. useIsForbidden(props.isForbidden);
  189. useIsNotFound(props.isNotFound);
  190. useIsNotCreatable(props.isNotCreatable);
  191. useRedirectFrom(props.redirectFrom ?? null);
  192. useIsSharedUser(false); // this page cann't be routed for '/share'
  193. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  194. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  195. useIsSearchPage(false);
  196. useTemplateTagData(props.templateTagData);
  197. useTemplateBodyData(props.templateBodyData);
  198. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  199. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  200. useIsSearchServiceReachable(props.isSearchServiceReachable);
  201. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  202. useIsSlackConfigured(props.isSlackConfigured);
  203. // useIsMailerSetup(props.isMailerSetup);
  204. useIsAclEnabled(props.isAclEnabled);
  205. // useHasSlackConfig(props.hasSlackConfig);
  206. useDrawioUri(props.drawioUri);
  207. useHackmdUri(props.hackmdUri);
  208. // useNoCdn(props.noCdn);
  209. useDefaultIndentSize(props.adminPreferredIndentSize);
  210. useIsIndentSizeForced(props.isIndentSizeForced);
  211. useDisableLinkSharing(props.disableLinkSharing);
  212. useRendererConfig(props.rendererConfig);
  213. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  214. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  215. useIsAllReplyShown(props.isAllReplyShown);
  216. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  217. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  218. const { pageWithMeta, userUISettings } = props;
  219. const pageId = pageWithMeta?.data._id;
  220. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  221. useCurrentPageId(pageId ?? null);
  222. useRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  223. useRemoteRevisionId(pageWithMeta?.data.revision?._id);
  224. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  225. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  226. useCurrentPathname(props.currentPathname);
  227. useSWRxCurrentPage(undefined, pageWithMeta?.data ?? null); // store initial data
  228. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  229. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  230. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  231. useSetupGlobalSocket();
  232. useSetupGlobalSocketForPage(pageId);
  233. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName();
  234. const shouldRenderPutbackPageModal = pageWithMeta != null
  235. ? _isTrashPage(pageWithMeta.data.path)
  236. : false;
  237. // sync grant data
  238. useEffect(() => {
  239. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  240. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  241. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  242. useEffect(() => {
  243. const decodedURI = decodeURI(window.location.pathname);
  244. if (isClient() && decodedURI !== props.currentPathname) {
  245. const { search, hash } = window.location;
  246. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  247. }
  248. }, [props.currentPathname, router]);
  249. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  250. const title = generateCustomTitle(props, 'GROWI');
  251. const sideContents = !props.isNotFound && !props.isNotCreatable
  252. ? (
  253. <PageSideContents page={pageWithMeta?.data} />
  254. )
  255. : <></>;
  256. const footerContents = !props.isIdenticalPathPage && !props.isNotFound && pageWithMeta != null
  257. ? (
  258. <>
  259. { pagePath != null && !isTopPagePath && (
  260. <Comments pageId={pageId} pagePath={pagePath} revision={pageWithMeta.data.revision} />
  261. ) }
  262. { isUsersHomePage(pageWithMeta.data.path) && (
  263. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  264. ) }
  265. <PageContentFooter page={pageWithMeta.data} />
  266. </>
  267. )
  268. : <></>;
  269. return (
  270. <>
  271. <Head>
  272. <title>{title}</title>
  273. </Head>
  274. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  275. <header className="py-0 position-relative">
  276. <div id="grw-subnav-container">
  277. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  278. </div>
  279. </header>
  280. <div className="d-edit-none">
  281. <GrowiSubNavigationSwitcher />
  282. </div>
  283. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  284. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  285. <MainPane
  286. sideContents={sideContents}
  287. footerContents={footerContents}
  288. >
  289. <PageAlerts />
  290. { props.isIdenticalPathPage && <IdenticalPathPage />}
  291. { !props.isIdenticalPathPage && (
  292. <>
  293. { props.isForbidden && <ForbiddenPage /> }
  294. { props.isNotCreatable && <NotCreatablePage />}
  295. { !props.isForbidden && !props.isNotCreatable && <DisplaySwitcher />}
  296. </>
  297. ) }
  298. <PageStatusAlert />
  299. </MainPane>
  300. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  301. </div>
  302. </>
  303. );
  304. };
  305. Page.getLayout = function getLayout(page) {
  306. return (
  307. <>
  308. <DrawioViewerScript />
  309. <BasicLayoutWithEditorMode>
  310. {page}
  311. </BasicLayoutWithEditorMode>
  312. <UnsavedAlertDialog />
  313. <DescendantsPageListModal />
  314. <DrawioModal />
  315. <HandsontableModal />
  316. </>
  317. );
  318. };
  319. function getPageIdFromPathname(currentPathname: string): string | null {
  320. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  321. }
  322. class MultiplePagesHitsError extends ExtensibleCustomError {
  323. pagePath: string;
  324. constructor(pagePath: string) {
  325. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  326. this.pagePath = pagePath;
  327. }
  328. }
  329. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  330. const { model: mongooseModel } = await import('mongoose');
  331. const req: CrowiRequest = context.req as CrowiRequest;
  332. const { crowi } = req;
  333. const { revisionId } = req.query;
  334. const Page = crowi.model('Page') as PageModel;
  335. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  336. const { pageService } = crowi;
  337. let currentPathname = props.currentPathname;
  338. const pageId = getPageIdFromPathname(currentPathname);
  339. const isPermalink = _isPermalink(currentPathname);
  340. const { user } = req;
  341. if (!isPermalink) {
  342. // check redirects
  343. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  344. if (chains != null) {
  345. // overwrite currentPathname
  346. currentPathname = chains.end.toPath;
  347. props.currentPathname = currentPathname;
  348. // set redirectFrom
  349. props.redirectFrom = chains.start.fromPath;
  350. }
  351. // check whether the specified page path hits to multiple pages
  352. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  353. if (count > 1) {
  354. throw new MultiplePagesHitsError(currentPathname);
  355. }
  356. }
  357. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  358. const page = pageWithMeta?.data as unknown as PageDocument;
  359. // add user to seen users
  360. if (page != null && user != null) {
  361. await page.seen(user);
  362. }
  363. // populate & check if the revision is latest
  364. if (page != null) {
  365. page.initLatestRevisionField(revisionId);
  366. await page.populateDataToShowRevision();
  367. props.isLatestRevision = page.isLatestRevision();
  368. }
  369. if (page == null && user != null) {
  370. const templateData = await Page.findTemplate(props.currentPathname);
  371. if (templateData != null) {
  372. props.templateTagData = templateData.templateTags as string[];
  373. props.templateBodyData = templateData.templateBody as string;
  374. }
  375. }
  376. props.pageWithMeta = pageWithMeta;
  377. }
  378. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  379. const { model: mongooseModel } = await import('mongoose');
  380. const req = context.req as CrowiRequest<IUserHasId & any>;
  381. const { user } = req;
  382. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  383. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  384. if (userUISettings != null) {
  385. props.userUISettings = userUISettings.toObject();
  386. }
  387. }
  388. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  389. const req: CrowiRequest = context.req as CrowiRequest;
  390. const { crowi } = req;
  391. const Page = crowi.model('Page') as PageModel;
  392. const { currentPathname } = props;
  393. const pageId = getPageIdFromPathname(currentPathname);
  394. const isPermalink = _isPermalink(currentPathname);
  395. const page = props.pageWithMeta?.data;
  396. if (props.isIdenticalPathPage) {
  397. props.isNotCreatable = true;
  398. }
  399. else if (page == null) {
  400. props.isNotFound = true;
  401. props.isNotCreatable = !isCreatablePage(currentPathname);
  402. // check the page is forbidden or just does not exist.
  403. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  404. props.isForbidden = count > 0;
  405. }
  406. else {
  407. props.isNotFound = page.isEmpty;
  408. props.isNotCreatable = false;
  409. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  410. if (isPermalink && page.isEmpty) {
  411. props.currentPathname = page.path;
  412. }
  413. // /path/to/page ==> /62a88db47fed8b2d94f30000
  414. if (!isPermalink && !page.isEmpty) {
  415. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  416. if (!isToppage) {
  417. props.currentPathname = `/${page._id}`;
  418. }
  419. }
  420. }
  421. }
  422. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  423. // const req: CrowiRequest = context.req as CrowiRequest;
  424. // const { crowi } = req;
  425. // const UserModel = crowi.model('User');
  426. // if (isUserPage(props.currentPagePath)) {
  427. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  428. // if (user != null) {
  429. // props.pageUser = JSON.stringify(user.toObject());
  430. // }
  431. // }
  432. // }
  433. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  434. const req: CrowiRequest = context.req as CrowiRequest;
  435. const { crowi } = req;
  436. const {
  437. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  438. } = crowi;
  439. props.isSearchServiceConfigured = searchService.isConfigured;
  440. props.isSearchServiceReachable = searchService.isReachable;
  441. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  442. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  443. // props.isMailerSetup = mailService.isMailerSetup;
  444. props.isAclEnabled = aclService.isAclEnabled();
  445. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  446. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  447. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  448. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  449. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  450. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  451. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  452. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  453. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  454. props.editorConfig = {
  455. upload: {
  456. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  457. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  458. },
  459. };
  460. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  461. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  462. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  463. props.rendererConfig = {
  464. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  465. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  466. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  467. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  468. plantumlUri: process.env.PLANTUML_URI ?? null,
  469. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  470. // XSS Options
  471. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  472. tagWhiteList: crowi.xssService.getTagWhiteList(),
  473. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  474. // XSS: rehype-sanitize options
  475. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  476. };
  477. props.sidebarConfig = {
  478. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  479. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  480. };
  481. }
  482. /**
  483. * for Server Side Translations
  484. * @param context
  485. * @param props
  486. * @param namespacesRequired
  487. */
  488. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  489. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  490. props._nextI18Next = nextI18NextConfig._nextI18Next;
  491. }
  492. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  493. const req = context.req as CrowiRequest<IUserHasId & any>;
  494. const { user } = req;
  495. const result = await getServerSideCommonProps(context);
  496. // check for presence
  497. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  498. if (!('props' in result)) {
  499. throw new Error('invalid getSSP result');
  500. }
  501. const props: Props = result.props as Props;
  502. if (props.redirectDestination != null) {
  503. return {
  504. redirect: {
  505. permanent: false,
  506. destination: props.redirectDestination,
  507. },
  508. };
  509. }
  510. if (user != null) {
  511. props.currentUser = user.toObject();
  512. }
  513. try {
  514. await injectPageData(context, props);
  515. }
  516. catch (err) {
  517. if (err instanceof MultiplePagesHitsError) {
  518. props.isIdenticalPathPage = true;
  519. }
  520. else {
  521. throw err;
  522. }
  523. }
  524. await injectUserUISettings(context, props);
  525. await injectRoutingInformation(context, props);
  526. injectServerConfigurations(context, props);
  527. await injectNextI18NextConfigurations(context, props, ['translation']);
  528. return {
  529. props,
  530. };
  531. };
  532. export default Page;